let mydebug = require('./mydebug')
let noble = require('@abandonware/noble');
let events = require('events');

let controllerEvent = new events.EventEmitter();

let Service_UUID = "c163008a41534200a9a30b6a19f90de8";
let Temperature_UUID = "307b05aa18ff4e929ab19977ea66a808";
let Channel1_UUID = "a0ee03ca616c48c3a8a72afc5586d90a";
let Channel2_UUID = "51b8a85c252b46bd85b5a2170b04aeb2";
let Channel3_UUID = "6e03f24bee914cf5a2569c4f58aeff0f";

let ControllerService = null;
let TemperatureChar = null;
let ChannelChars = [null, null, null];

let Controller_Address = "c5:64:c6:ef:b4:58";
let lightController = null;

function setLEDpwm(channel, pwm) {
    if (ChannelChars[channel] === null) {
        return;
    }

    let val = Buffer.alloc(2);
    val.writeUInt16LE(pwm, 0);
    ChannelChars[channel].write(val, false);
}

noble.on('stateChange', function (state) {
    if (state === 'poweredOn') {
        noble.startScanning();
    } else {
        noble.stopScanning();
    }
});

noble.on('scanStart', function() {
    mydebug.LogOutput('on -> scanStart');
});

noble.on('scanStop', function() {
    mydebug.LogOutput('on -> scanStop');
});

function controller_connect() {
    mydebug.LogOutput('on -> connect');

    let chars = [Temperature_UUID, Channel1_UUID, Channel2_UUID, Channel3_UUID];
    lightController.discoverSomeServicesAndCharacteristics([Service_UUID], chars, function(err, services, characteristics) {
        mydebug.LogOutput('found service:', services);
        mydebug.LogOutput('-----------------------------');
        mydebug.LogOutput('found chars:', characteristics);

        TemperatureChar = characteristics[0];
        ChannelChars[0] = characteristics[1];
        ChannelChars[1] = characteristics[2];
        ChannelChars[2] = characteristics[3];

        controllerEvent.emit('connect');
    });
}

function controller_disconnect() {
    mydebug.LogOutput('on -> disconnect');

    ControllerService = null;
    TemperatureChar = null;
    ChannelChars = [null, null, null];

    controllerEvent.emit('disconnect');

    noble.startScanning();
}

noble.on('discover', function (peripheral) {
    if (peripheral.address !== Controller_Address) {
        return;
    }

    noble.stopScanning();

    if (lightController === null) {
        lightController = peripheral;
        lightController.on('connect', controller_connect);
        lightController.on('disconnect', controller_disconnect);
    }

    lightController.connect();
});

exports.setLEDpwm = setLEDpwm;
exports.controllerEvent = controllerEvent;
